﻿using JMS;
using JMS.IdentityModel.JWT.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection.PortableExecutable;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace BusinessServiceHost.Controllers
{
    public class DemoController : BaseController
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userid">直接传用户id，直接返回token</param>
        /// <returns></returns>
        public string Login(long userid)
        {
            //直接生成jwt token
            var claims = new Claim[]
             {
                    new Claim(ClaimTypes.NameIdentifier, userid.ToString())
             };

            //token有效期1年
            var time = DateTime.Now.AddYears(1);

            var token = JwtHelper.GenerateToken(claims, "mysuperret_secretkey!123", time);

            return token;
        }

        /// <summary>
        /// 初始化所有测试数据
        /// </summary>
        /// <returns>产品id</returns>
        public async Task<int> InitDatas(int count)
        {
            using ( var rc = new RemoteClient(Global.GatewayAddresses))
            {
                var productService = await rc.GetMicroServiceAsync("ProductService");
                var assetService = await rc.GetMicroServiceAsync("AssetService");

                //开启分布式事务
                rc.BeginTransaction();

                //创建一个产品
                var productId = await productService.InvokeAsync<int>("AddProduct", new {
                    Name = "Product1",
                    TotalQuantity = 20000,
                    Quantity = 20000,
                    Price = 5000, 
                    PromotionId = Guid.NewGuid().ToString("N")
                });

                //创建资金账户
                for(int i = 0; i < count; i++)
                {
                    var userid = i + 1;
                    var balance = 10000m;
                    assetService.InvokeAsync("AddMoneyAccount", userid, balance);
                }

                //提交事务
                await rc.CommitTransactionAsync();

                return productId;
            }
        }



        /// <summary>
        /// 购买商品
        /// </summary>
        /// <param name="productId">商品id</param>
        /// <param name="quantity">数量</param>
        /// <returns></returns>
        [JMS.Authorize]
        public async Task<decimal> Buy(int productId,int quantity)
        {
            var userid = int.Parse( this.UserContent.FindFirst(ClaimTypes.NameIdentifier).Value);

            //假设商品单价为
            using (var rc = new RemoteClient(Global.GatewayAddresses))
            {
                var productService = await rc.GetMicroServiceAsync("ProductService");
                var assetService = await rc.GetMicroServiceAsync("AssetService");

                //开启分布式事务
                rc.BeginTransaction();

                //下单，获取支付金额
                var amount = await productService.InvokeAsync<decimal>("CreateOrder", userid, productId, quantity);

                //支付 
                assetService.InvokeAsync("Pay", userid, amount);

                //提交事务
                await rc.CommitTransactionAsync();

                return amount;
            }

        }
    }
}
